import { defineStore } from "pinia";
import { ref } from "vue";
import { 
  selectPlanById, 
  updatePlan as apiUpdatePlan,
  createPlan as apiCreatePlan,
 selectPlansByUserId
} from "@/api/plan";
import { ElMessage } from "element-plus";

export const usePlanStore = defineStore("plan", () => {
  const currentPlan = ref<any | null>(null);
  
  // 设置当前计划
  const setCurrentPlan = (plan: any) => {
    currentPlan.value = plan;
  };

  // 根据ID获取计划
  const fetchPlanById = async (planId: number) => {
    try {
      const response = await selectPlanById(planId);
      currentPlan.value = response.data;
      return response.data;
    } catch (error) {
      ElMessage.error('获取计划失败');
      console.error(error);
      return null;
    }
  };

  // 根据用户ID获取计划
  const getPlansByUserId = async (userId: string) => {
    try {
      const response = await selectPlansByUserId(userId);
      return response;
    } catch (error) {
      console.error('获取用户计划失败:', error);
      throw error;
    }
  };

  // 更新整个计划
  const updatePlan = async (planData: any) => {
    try {
      const response = await apiUpdatePlan(planData);
      currentPlan.value = response.data;
      ElMessage.success('计划更新成功');
      return response.data;
    } catch (error) {
      ElMessage.error('更新计划失败');
      console.error(error);
      throw error;
    }
  };

  // 创建新计划
  const createNewPlan = async (planData: any) => {
    try {
      const response = await apiCreatePlan(planData);
      currentPlan.value = response.data;
      ElMessage.success('计划创建成功');
      return response.data;
    } catch (error) {
      ElMessage.error('创建计划失败');
      console.error(error);
      throw error;
    }
  };

  // 计算计划进度
  const calculatePlanProgress = (plan: any) => {
    if (!plan?.weeks?.length) return 0;
    
    let totalTasks = 0;
    let completedTasks = 0;
    
    plan.weeks.forEach((week: any) => {
      week.content.forEach((task: any) => {
        totalTasks++;
        if (task.status) completedTasks++;
      });
    });
    
    return totalTasks > 0 ? Math.round((completedTasks / totalTasks) * 100) : 0;
  };

  return {
    currentPlan,
    setCurrentPlan,
    fetchPlanById,
    updatePlan,
    getPlansByUserId,
    createNewPlan,
    calculatePlanProgress
  };
}, {
  persist: true,
});